package com.yb.project.system.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yb.common.domain.AjaxObject;
import com.yb.common.utils.StringUtil;
import com.yb.framework.log.annotation.Log;
import com.yb.framework.log.enums.OperateTypeEnum;
import com.yb.project.base.controller.BaseController;
import com.yb.project.system.domain.SysMenu;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/system/menu")
@Api(tags = "菜单管理")
public class SysMenuController extends BaseController {
	
	Logger logger = LoggerFactory.getLogger(SysMenuController.class.getName());
	
	private static String SYS_MENU = "system/menu/menu";
	private static String SYS_MENU_ADD = "system/menu/menu_add";
	private static String SYS_MENU_EDIT = "system/menu/menu_edit";
	
	@GetMapping("")
	@PreAuthorize("hasAuthority('system:menu')")
	public String main() {
		return SYS_MENU;
	}
	
	@GetMapping("/add_view")
	@PreAuthorize("hasAuthority('system:menu:add')")
	public String addView() {
		return SYS_MENU_ADD;
	}
	
	@GetMapping("/edit_view/{id}")
	@PreAuthorize("hasAuthority('system:menu:edit')")
	public String editView(@PathVariable("id") Long id, ModelMap model) {
		model.put("sysMenu", sysMenuService.getById(id));
		return SYS_MENU_EDIT;
	}
	
	/**
	 * 菜单列表
	 */
	@PostMapping("/list/{id}")
	@PreAuthorize("hasAuthority('system:menu:list')")
	@ApiOperation(value="菜单列表", notes="根据父ID查询角色信息")
	public @ResponseBody List<SysMenu> list(@PathVariable("id") Long pid, SysMenu sysMenu) {
		List<SysMenu> sysMenuList = new ArrayList<SysMenu>();
		if(pid == -1) {
			// 菜单初始化，查找顶层菜单
			sysMenu.setId(null);
			sysMenu.setPid(0L);
			List<SysMenu> topMenus = sysMenuService.getPageByEntity(sysMenu);
			//List<SysMenu> topMenus = sysMenuService.getListByPid(0L);
			for (SysMenu topMenu : topMenus) {
				// state设置为closed，否则菜单树无法展开
				topMenu.setState("closed");
				sysMenuList.add(topMenu);
			}
		} else {
			// 通过父ID查找所有子级菜单
			sysMenu.setId(null);
			sysMenu.setPid(pid);
			List<SysMenu> childMenus = sysMenuService.getPageByEntity(sysMenu);
			//List<SysMenu> topMenus = sysMenuService.getListByPid(pid);
			for (SysMenu childMenu : childMenus) {
				childMenu.setState("closed");
				sysMenuList.add(childMenu);
			}
		}
		return sysMenuList;
	}
	
	/**
	 * 新增菜单
	 */
	@PostMapping("/add")
	@PreAuthorize("hasAuthority('system:menu:add')")
	@ApiOperation(value="新增菜单", notes="新增菜单信息")
	@Log(label = "新增菜单", operateType = OperateTypeEnum.ADD)
	public @ResponseBody AjaxObject add(SysMenu sysMenu) {
		SysMenu parent = sysMenuService.getById(sysMenu.getPid());
		sysMenu.setLevel(parent.getLevel() + 1);
		return toAjax(sysMenuService.insert(sysMenu), "新增菜单" + "[" + sysMenu.getName() + "]");
	}
	
	/**
	 * 编辑菜单
	 */
	@PostMapping("/edit")
	@PreAuthorize("hasAuthority('system:menu:edit')")
	@ApiOperation(value="编辑菜单", notes="编辑菜单信息")
	@Log(label = "编辑菜单", operateType = OperateTypeEnum.EDIT)
	public @ResponseBody AjaxObject edit(SysMenu sysMenu) {
		SysMenu parent = sysMenuService.getById(sysMenu.getPid());
		sysMenu.setLevel(parent.getLevel() + 1);
		return toAjax(sysMenuService.update(sysMenu), "编辑菜单" + "[" + sysMenu.getName() + "]");
	}
	
	/**
	 * 删除菜单
	 */
	@PostMapping("/delete")
	@PreAuthorize("hasAuthority('system:menu:delete')")
	@ApiOperation(value="删除菜单", notes="批量删除菜单信息")
	@Log(label = "删除菜单", operateType = OperateTypeEnum.DELETE)
	public @ResponseBody AjaxObject delete(@RequestParam("ids") String ids) {
		List<String> sysMenuNames = sysMenuService.getNamesByIds(StringUtil.str2LongArray(ids));
		return toAjax(sysMenuService.deleteListByIds(StringUtil.str2LongArray(ids)), "批量删除菜单" + sysMenuNames);
	}
	
	/**
	 * 获取节点的所有父ID（返回格式："id1, id2, id3"）
	 */
	@RequestMapping("/getFatherIds/{id}")
	public @ResponseBody String getFatherIds(@PathVariable Long id) {
		return StringUtil.list2String(sysMenuService.getAllParentIds(id));
	}
}